<template>
  <div class="authentication">
    <div class="common" v-if="!showPage">
      <div class="title_model" v-show="!showTitle">
        <div @click="onBtn(1)" :class="active==1? 'active':'unactive' ">
          <p>选择类型</p>
          <p><img src="../../../static/fuel/right.png" alt=""></p>
        </div>
        <div @click="onBtn(2)" :class="active==2? 'active':'unactive' ">
          <p>填写信息</p>
          <p><img src="../../../static/fuel/right.png" alt=""></p>
        </div>
        <div @click="onBtn(3)" :class="active==3? 'active':'unactive' ">
          <p>上传截图</p>
          <p><img src="../../../static/fuel/right.png" alt=""></p>
        </div>
        <div @click="onBtn(4)" :class="active==4? 'active':'unactive' ">
          <p><img src="../../../static/fuel/unfinish.png" alt=""></p>
        </div>
      </div>
      <!-- 选择类型 -->
      <div v-if="active==1">
        <div v-for="item in list">
          <div class="myCar_type">
            <p>{{item.carTypeName}}</p>
          </div>
          <van-grid :column-num="3" :border="false">
            <van-grid-item v-for="(subitem,index) in item.carList" :key="item.id"  :icon="subitem.categoryImageUrl" :text="subitem.categoryName"  @click="onFillInfo(subitem.id)"/>
          </van-grid>
        </div>
        <div v-if="list.length==0">
          <van-empty description="暂无渠道列表" />
        </div>
      </div>
      <!-- 填写信息 -->
      <div v-if="active==2" class="info_model">
        <div>
          <p>姓名</p>
          <p class="inputField"><van-field @input="RegExpString(userName)" v-model="userName" maxlength="20"/></p>
        </div>
        <div>
          <p>手机号</p>
          <p class="inputField"><van-field @input="handleInput(mobilePhone)" maxlength="11" v-model="mobilePhone"/></p>
        </div>
        <div>
          <p>车牌号</p>
          <p  @click="showKeybord = true" class="inputField"><van-field :readonly="true" v-model="plateNumber" maxlength="10"/></p>
           <vnp-keyboard v-model="plateNumber" :show.sync="showKeybord"></vnp-keyboard>
           <!-- <van-cell-group>
              <van-field :value="plateNumber" readonly label="车牌号" @click="showKeybord = true" />
            </van-cell-group>
          <vnp-keyboard v-model="plateNumber" :show.sync="showKeybord"></vnp-keyboard> -->
        </div>
        <div class="next" @click="onNext"><p>下一步</p></div>
      </div>
      <!-- 上传截图 -->
      <div v-if="active==3" class="printscreen_model">
        <p>上传截图</p>
        <van-uploader :max-size="5*1024*1024"  :before-read="beforeRead" @oversize="onOversize" v-model="fileList" multiple :max-count="9"/>
        <div class="finish" @click="onFinish"><p>提交审核</p></div>
      </div>
      <!-- 完成 -->
      <div class="finish_model" v-if="active==4" >
        <div v-if="status=='IN_REVIEW'">
          <p><img src="../../../static/fuel/complete.png" alt=""></p>
          <p>等待审核</p>
          <p>提交时间：{{createTime}}</p>
        </div>
        <div v-if="status=='PASS'">
          <div class="sucess_model">
            <div>车主申请成功</div>
            <div>加入日期：{{createTime}}</div>
          </div>
          <div class="sucess_info">您的申请已通过审核，可享受站点指定优惠，详情请咨询加油站工作人员</div>
        </div>
        <div v-if="status=='FAIL'">
          <div><p><img src="../../../static/fuel/fail.png" alt=""></p></div>
          <div>
            <p>审核被驳回，请检查审核内容后，重新提交审核</p>
            <p>审核意见：{{info.auditOpinion||'暂无审核意见'}}</p>
          </div>
          <div class="action_btn">
            <p @click="goBack">返回</p>
            <p @click="resubmit">重新提审</p>
          </div>
        </div>
      </div>
    </div>
    <div class="common" v-else>
      <div v-for="(item,index) in list2">
        <!-- 待审核 -->
        <div class="status_modal" v-if="item.status=='IN_REVIEW'">
            <p class="status_icon"><img src="../../../static/fuel/complete.png" alt=""></p>
            <div class="status_right">
              <p>审核状态：待审核</p>
              <p>手机号码：{{item.mobilePhone}}</p>
              <p>渠道名称：{{item.businessName}}</p>
              <p>类型名称: {{getPropertyById(item.businessId).categoryName}}</p>
              <p>提交时间：{{item.createTime}}</p>
            </div>
        </div>
        <!-- 审核通过 -->
        <div class="status_modal" v-if="item.status=='PASS'">
            <p class="status_icon"><img src="../../../static/fuel/complete.png" alt=""> </p>
            <div class="status_right">
              <p>审核状态：加入成功</p>
              <p>手机号码：{{item.mobilePhone}}</p>
              <p>渠道名称：{{item.businessName}}</p>
              <p>类型名称: {{getPropertyById(item.businessId).categoryName}}</p>
              <p>提交时间：{{item.createTime}}</p>
            </div>
        </div>
        <!-- 审核失败 -->
        <div class="status_modal" v-if="item.status=='FAIL'" @click="onReset(item)">
            <p class="status_icon"><img src="../../../static/fuel/fail.png" alt=""> </p>
            <div class="status_right">
              <p>审核状态：审核失败</p>
              <p>手机号码：{{item.mobilePhone}}</p>
              <p>渠道名称：{{item.businessName}}</p>
              <p>类型名称: {{getPropertyById(item.businessId).categoryName}}</p>
              <p>审核意见：{{item.auditOpinion||'暂无审核意见'}}</p>
              <p>提交时间：{{item.createTime}}</p>
            </div>
        </div>
      </div>
    </div>
    <van-action-sheet v-model="showPop" :close-on-click-overlay="false" close-on-click-action cancel-text="取消" :actions="stationList" @select="onSelect" />
  </div>
</template>

<script>
import Keyboard from '@/components/vant-number-plate/vnp-keyboard.vue'
import { mapGetters } from "vuex";
import { getAuthen } from "@/utils/getAuthen";
import Vue from "vue";
import { Step, Steps, Grid, GridItem,Field,Uploader,Toast,ActionSheet,Empty  } from 'vant';
Vue.use(Step);
Vue.use(Steps);
Vue.use(Grid);
Vue.use(GridItem);
Vue.use(Field);
Vue.use(Uploader);
Vue.use(Toast);
Vue.use(ActionSheet);
Vue.use(Empty);
export default {
  head() {
    return {
      title: "选择认证类型"
    };
  },
  components:{ 
    'vnp-keyboard': Keyboard,
  },
  data() {
    return {
      active: 1,
      list:[],
      userName:'',//姓名
      mobilePhone:'',//手机号
      plateNumber:'',//车牌号
      fileList:[],//截图
      id:null,
      showKeybord:false,//汽车输入键盘
      status:'',//审核状态
      createTime:'',//创建时间
      showTitle:false,//是否展示tab栏
      showPop:false,
      info:'',
      stationList:[],//油站列表
      stationId:null,//油站id
      businessStatus:null,//是否停用 1删除/未启动     0未删除
      disabled:false,
      isAudit:null,
      list2:[],
      showPage:false
    };
  },
  computed:{
    ...mapGetters({
      userInfo: "authen/userInfo"
    }),
  },
  created(){
    if(this.userInfo.userId){ 
      this.getData()
      this.getStation()
    }else{ 
      getAuthen();
    }
  },
  mounted(){
    this.getStatus()
  },
  methods:{ 
    async getStatus(){
      const params={ 
        enterpriseId:this.enterpriseId,
        userId:this.userInfo.userId,
        businessName:'label_rule',
      }
      if(this.isAudit==0||this.isAudit==1){
        params['businessId']=this.id
      } 
      const res=await this.$axios.$post('/businessAudit/queryLatestAuditNew',params)
      if(res&&res.code==200){ 
        if(res&&res.result&&res.result.length){ 
          this.list2=res.result||[]
          this.showPage=true
          if(this.isAudit==0||this.isAudit==1){
            if(res.result.length==1){ 
              let info=res&&res.result&&res.result[0]
              if(info.status=='FAIL'){ 
                this.showPop=true
              }else if(info.status=='IN_REVIEW'){ 
                this.$toast(`当前手机号为${info.mobilePhone}已在${info.businessName}存在一条审核记录，请勿重复操作`,{duration:2000})
              }
            }else if(res.result.length==2){ 
              this.showPop=false
            }
          }else{
            if(this.list2.length==2){ 
              if (res.result.every(item => item.status == 'FAIL')) {
                this.list2 = [];
                this.showPage = false;
                this.$toast('您当前所有申请失败，请重新进行渠道认证',{duration:2000})
              }
            }
          }
        }else{ 
          this.showTitle=false
          this.showPop=true
          this.getData()
        }
      }else{ 
        this.$toast.fail((res&&res.msg),{ duration: 1500})
      }
    } ,
    onReset(item){
      if(this.list2.length==1&&item.status=='FAIL'){ 
        this.showPop=true
        this.info=item
        this.showPage=false
        this.resubmit()
      }else{ 
        if(this.list2.length==2){
          if(this.list2.some(item=>item.status=='IN_REVIEW')){
            this.$toast('您当前存在一条待审核记录，无法进行操作',{duration:2000})
          }
         }
      }
    },
    beforeRead(file) {
      const isTIFF = file.type === 'image/tiff' || file.type === 'image/tif';
      if (isTIFF) {
        this.$toast.fail('上传图片不能为TIFF格式！');
      }
      return !isTIFF;
    },
    onOversize(file) {
      this.$toast.fail('文件大小不能超过 5M');
    },
    async onSelect(item){
      this.stationId=item.stationId
      this.showPop=false
      if(this.isAudit==0||this.isAudit==1){ 
        const params={ 
          businessId:this.id,
          enterpriseId:this.enterpriseId,
          businessName:'label_rule',
          userId:this.userInfo.userId,
          stationId:this.stationId,
          mobilePhone:this.phone,
          source:this.isAudit==1 ?2:1
        }
        const res= this.isAudit==0? await this.$axios.$post('/businessAudit/addBusinessV2',params):await this.$axios.$post('/businessAudit',params)
        if(res&&res.code==200){ 
            if(this.isAudit==0||this.isAudit==1){
              const currentDate = new Date();
              this.createTime = this.formatDateTime(currentDate);
              window.location.reload();
            }else{ 
              this.showTitle=true
              this.status=res&&res.result.status||''
              this.createTime=res&&res.result.createTime||''
              this.active=4
            } 
        }else{ 
          this.$toast.fail(res&&res.msg)
        }
      }else if(this.list2.length){

      } 
    },
    async getStation(){
     const res=await this.$axios.$get("/selectStaInfoList", {params: {enterpriseId: this.enterpriseId}})
      if(res&&res.retCode==0){
        this.stationList=this.stationActions = res.data.map(ele => {
          return { ...ele, name: ele.stationName };
        });
      }else{ 
        this.$toast.fail(res&&res.message)
      }
    },
    async getData(){
      const res=await this.$axios.$get('/ruleLabelList',{
        params:{enterpriseId:this.enterpriseId }
      })
      if(res&&res.retCode==0){ 
        this.list=res.data||[]
      }else{ 
        throw new Error(res&&res.message);
      }
    },
    onBtn(step){ 
      if(this.list.length){ 
        if(!this.disabled){ 
          if(step<=this.active){ 
            if (step >= 1 && step <= 4) {
              this.active = step;
            } else {
              this.disabled=true
              this.$toast.fail('暂无渠道列表，无法进行申请')
            }
          }
        }
      }else{ 
        this.disabled=true
        this.$toast.fail('暂无渠道列表，无法进行申请')
      }
    },
    onFillInfo(id){
      this.id=id 
      this.active=2
    },
    //下一步
    onNext(){
      if(this.userName&&this.mobilePhone&&this.plateNumber){ 
        if(this.mobilePhone.length==11){ 
          this.active=3
        }else{ 
          this.$toast.fail('请输入11位手机号~')
        }
      }else{ 
        this.$toast.fail('请填写完整的信息~~')
      }
      
    },
    //提交审核
    async onFinish(){ 
      let fileLists=[]
       let formData = new FormData();
      // 遍历 fileList 中的文件，添加到 FormData
      this.fileList.forEach(file => {
        formData.append('files', file.file);
      });

     const response=await this.$axios.$post('/common/admin/uploadFile',formData)
     if(response&&response.retCode==0){ 
        fileLists=response.data
      }else{ 
        this.$toast.fail(res&&res.msg)
      }
      if(this.id&&this.userName&&this.stationId&&this.mobilePhone&&this.plateNumber){ 
        const params={ 
          businessId:this.id,
          mobilePhone:this.mobilePhone,
          plateNumber:this.plateNumber,
          enterpriseId:this.enterpriseId,
          businessName:'label_rule',
          userId:this.userInfo.userId,
          userName:this.userName,
          files:fileLists ? fileLists.join(', '):null,
          stationId:this.stationId
        }
        if(this.isAudit!=null){ 
          params['isAudit']=this.isAudit
        }
        const res=await this.$axios.$post("/businessAudit",params)
        if(res&&res.code==200){ 
          this.showTitle=true
          this.status=res&&res.result.status||''
          this.createTime=res&&res.result.createTime||''
          this.active=4
        }else{ 
          this.$toast.fail(res&&res.msg)
        }
      }else{ 
        if(!this.stationId){ 
          this.showPop=true
          this.$toast.fail('请选择油站~')
        }else{
          this.$toast.fail('请填写完整的信息~~')
        }
      }
    },
    // 查询审核状态
    // async seachStatus(){
    //    const res=await this.$axios.$post('/businessAudit/queryLatestAudit',{ 
    //       businessName:'label_rule',
    //       enterpriseId:this.enterpriseId,
    //       userId:this.userInfo.userId||null
    //    })
    //    if(res&&res.code==200){ 
    //       if(res.result){ 
    //         if((this.isAudit==0||this.isAudit==1)&&res.result.status=='FAIL'){ 
    //           this.showPop=true
    //           this.active=null
    //           this.showTitle=true
    //         }else{ 
    //           if (res && res.result && res.result.status === 'PASS') {
    //             if (res.result.labelName) {
    //               this.$toast(`您当前存在于${res.result.labelName}-${res.result.categoryName}渠道里面`,{ duration: 1500});
    //             } else if (res.result.businessId) {
    //               const response = await this.$axios.$get(`/businessAudit/queryById/${res.result.businessId}`);
    //               this.$toast(`您当前存在于${response.labelName}-${response.categoryName}渠道里面`,{ duration: 1500})
    //             }
    //           }
    //           if(res && res.result && res.result.status=='IN_REVIEW'){ 
    //             let propertyName =this.getPropertyById(res.result.businessId);
    //             this.$toast(`您已提交到${propertyName.labelName}-${propertyName.categoryName}渠道里面，请等待耐心审核`,{ duration: 1500})
    //           }
    //           this.status=res.result.status||''
    //           this.info=res.result||''
    //           this.active=4
    //           this.showTitle=true
    //           this.createTime=res.result.createTime||''
    //           this.businessStatus=res.result.businessStatus
    //           if(this.businessStatus==1){ 
    //             this.active=1
    //             this.showTitle=false
    //           }
    //         }
            
    //       }else{
    //           this.showTitle=false
    //           this.showPop=true
    //           this.getData()
    //         // }
    //       } 
    //    }else{ 
    //     this.$toast.fail(res&&res.msg)
    //    }
    // },
    getPropertyById(id) {
    let item = this.list.find(item => {
        return item.carList.some(card => card.id == id);
    });
    if (item) {
        let card = item.carList.find(card => card.id == id);
        return {labelName:card.labelName,categoryName:card.categoryName,} // 返回ID为2的项目的名称属性
    } else {
        return null; // 如果找不到对应ID的项目，返回null
    }
  },
    // 返回
    goBack(){ 
      this.$router.go(-1)
    },
    // 校验特殊字符
    RegExpString(str) {
      let p = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？《》 ]");
      if (p.test(str)) {
        this.$toast.fail('请不要输入特殊字符~');
        this.userName = '';
      } 
    },
    //校验数字
    handleInput(value) {
      // 检查用户输入是否只包含数字
      if (/^\d+$/.test(value)) {
        // 如果输入只包含数字，可以继续其他处理逻辑...
        this.mobilePhone = value; // 或者直接赋值
      } else {
        // 如果输入包含非数字字符，可以进行相应处理，例如清空输入
        this.$toast.fail('只能输入数字~');
        this.mobilePhone = '';
      }
    }, 
    // 重新提审
    resubmit(){
      this.getData()
      this.showTitle=false
      if(this.businessStatus==0){ 
        this.showPop=true
        this.active=2
        this.id=this.info.businessId
        this.userName=this.info.userName
        this.mobilePhone=this.info.mobilePhone
        this.plateNumber=this.info.plateNumber
        
      }else{ 
        this.showPop=false
        this.active=1
        this.id=null
        this.userName=this.info.userName
        this.mobilePhone=this.info.mobilePhone
        this.plateNumber=this.info.plateNumber
        this.onBtn(5)
      }
    },
    formatDateTime(date) {
      const year = date.getFullYear();
      const month =this.padZero(date.getMonth() + 1);
      const day = this.padZero(date.getDate());
      const hour =this.padZero(date.getHours());
      const minute =this.padZero(date.getMinutes());
      const second =this.padZero(date.getSeconds());
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
    padZero(num) {
      return num < 10 ? '0' + num : num;
    }
  },
  beforeRouteEnter(to,from,next){
    const isAudit=to.query.isAudit
    const id=to.query.id
    next(vm=>{ 
      vm.isAudit=isAudit
      vm.id=id
    })
  }
}
</script>

<style lang="scss" scoped>
.authentication {
  width: 100%;
  height: 100%;
  background-color: #fff;
  color: #333;
  overflow: auto;
  .common {
    background-color: #fff;
    .status_modal{ 
      display: flex;
      margin: 10px 16px 0;
      text-align: center;
      font-size: 14px;
      text-align: left;
      color: #fff;
      align-items: center;
      .status_icon{
        width: 1rem;
        height: 1rem;
        img{ 
          width: 100%;
          height: 100%;
        }
      } 
      .status_right{
        flex: 1;
        background-color:#918efb ;
        padding-left: 0.4rem;
        border-radius: 0.25rem;
      }
      
    }
    .title_model {
      position: sticky;
      top: 0;
      z-index: 100;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px 16px 0;
      background-color: #fff;

      .unactive {
        display: flex;
        align-items: center;
        font-size: 17px;

        p:first-child {
          color: #dddedf;
        }

        p:last-child {
          width: 20px;
          height: 20px;

          img {
            width: 100%;
            height: 100%;
          }
        }
      }

      .active {
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: bold;

        p:first-child {
          position: relative;
          color: #42a95d;
        }

        p:first-child::after {
          position: absolute;
          content: "";
          display: block;
          margin-top: 5px;
          width: 100%;
          height: 3px;
          border-radius: 6px;
          background-color: #42a95d;
        }

        p:last-child {
          width: 20px;
          height: 20px;

          img {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
    .myCar_type {
      overflow: auto;
      padding: 5px 30px;
      background-color: #f7f8f9;
      color: #9e9fa0;
      font-size: 16px;
    }
    /deep/.van-grid-item  .van-grid-item__icon{ 
      font-size: 65px;
    }
    /deep/.van-grid-item__text{ 
      font-size: 17px;
    }
    .info_model{ 
      padding: 10px 16px 0;
      background-color: #fff;
      /deep/ .van-cell{ 
        padding: 10px;
        line-height: 45px;
        .van-field__value{ 
          border: 0.5px solid #dbdbdb;
          border-radius: 6px;
        }
      }
      /deep/.van-field__control{ 
        padding-left: 20px;
      }
      div > p:first-child{ 
        font-size: 13px;
        font-weight: bold;
      }
      div{ 
        .inputField{ 
          padding: 0;
        }
      }
      .next{ 
        position:fixed;
        bottom: 40px;
        left: 16px;
        right: 16px;
        text-align: center;
        p{ 
          background-color: #169bd5;
          padding: 10px 0;
          font-size: 13px;
          color: #fff;
          border-radius: 6px;
        }
      }
    }
    .printscreen_model{ 
      padding: 10px 16px 0;
      background-color: #fff;
      font-size: 13px;
      font-weight: bold;
      /deep/.van-uploader__preview{ 
        margin: 10px;
      }
      /deep/.van-uploader__upload{ 
        margin: 10px;
      }
      .finish{ 
        position:fixed;
        bottom: 40px;
        left: 16px;
        right: 16px;
        text-align: center;
        p{ 
          background-color: #169bd5;
          padding: 10px 0;
          font-size: 13px;
          color: #fff;
          border-radius: 6px;
        }
      }
    }
    .finish_model{
      padding: 10px 16px 0;
      background-color: #fff;
      text-align: center;
      font-size: 14px;
      .sucess_model{ 
        text-align: left;
        background-color:#918efb ;
        border-radius: 6px;
        color: #fff;
        font-size: 14px;
        div{ 
          padding: 20px 15px;
        }
        div:last-child{
          padding-top: 10px;
        } 
      }
      .sucess_info{
        margin-top: 30px;
        color: #a8a6a6;
        text-align: left;
        font-size: 14px;
      }
    }
    .action_btn{ 
      position: fixed;
      bottom: 20px;
      left: 16px;
      right: 16px;
      display: flex;
      justify-content: space-between;
      p{ 
        flex: 1;
        border: 1px solid #aba9fc;
        margin: 0 10px;
        padding: 10px 0;
        border-radius: 6px;
        font-size: 16px;
        color: #fff;
      }
      p:first-child{ 
        color: #918efb;
      }
      p:last-child{ 
        background-color: #918efb;
      }
    }
  }
}

</style>
